package com.seven.alert.config;

import com.seven.alert.condition.AliSmsCondition;
import com.seven.alert.condition.MailCondition;
import com.seven.alert.mail.IMailService;
import com.seven.alert.mail.impl.IMailServiceImpl;
import com.seven.alert.sms.SendSmsService;
import com.seven.alert.properties.Alert;
import com.seven.alert.properties.Ali;
import com.seven.alert.properties.Mail;
import com.seven.alert.properties.Sms;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * @Author seven
 * @Date 2021/1/21 10:54
 * @Description
 * @Version 1.0
 */
@EnableConfigurationProperties({Alert.class, Ali.class, Mail.class, Sms.class})
public class AlertAutoConfiguration {
    @Autowired
    Alert alert;

    @Conditional(AliSmsCondition.class)
    @ConditionalOnMissingBean(SendSmsService.class)
    @Bean
    public SendSmsService sendSms() {
        return new SendSmsService(alert.getSms().getAli());
    }

    @Bean
    @ConditionalOnMissingBean(MailProperties.class)
    public MailProperties mailProperties() {
        MailProperties mailProperties = new MailProperties();
        BeanUtils.copyProperties(alert.getMail(), mailProperties);
        return mailProperties;
    }

    @Bean
    @ConditionalOnMissingBean(JavaMailSender.class)
    @ConditionalOnBean(MailProperties.class)
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setProtocol(alert.getMail().getProtocol());
        javaMailSender.setHost(alert.getMail().getHost());
        javaMailSender.setUsername(alert.getMail().getUsername());
        javaMailSender.setPassword(alert.getMail().getPassword());
        javaMailSender.setDefaultEncoding(alert.getMail().getDefaultEncoding().toString());
        return javaMailSender;
    }


    @Conditional(MailCondition.class)
    @ConditionalOnMissingBean(IMailService.class)
    @Bean
    public IMailService iMailService() {
        System.out.println(alert.getMail());
        return new IMailServiceImpl(alert.getMail().getForm());
    }
}
